
#include "bufMap.h"
#include "buf.h"

//---------------------------------------------------------------
// insert entry mapping (file,pageNo) to frameNo;
// returns OK if OK, BUFMAPERROR if an error occurred
//---------------------------------------------------------------

const Status BufMap::insert(File* file, 
				const int pageNo, 
				const unsigned int frameNo) 
{
    map< pair<File*, const int>, unsigned int>::iterator it;
    pair <File*, const int> key = make_pair(file, pageNo);
    it = realBufMap.find(key);
    if(it == realBufMap.end())
    {
        realBufMap[key] = frameNo;
        return OK;
    }
    else
    {
        //already in map, error
        return BUFMAPERROR;
    }
}


//-------------------------------------------------------------------        
// Check if (file,pageNo) is currently in the buffer pool.  If so, 
// return corresponding frameNo. else return BUFMAPNOTFOUND
//-------------------------------------------------------------------

const Status BufMap::lookup(File* file, 
				const int pageNo,
				unsigned int & frameNo) const
{
    map< pair<File*, const int>, unsigned int>::const_iterator it;
    pair <File*, const int> key = make_pair(file, pageNo);
    it = realBufMap.find(key);
    if(it == realBufMap.end())
    {
        //can't find it
        return BUFMAPNOTFOUND;
    }
    else
    {
        frameNo = it->second;
        return OK;
    }
}


//-------------------------------------------------------------------
// delete entry (file,pageNo) from mapping. Return OK if page was
// found.  Else if the entry is not found, return BUFMAPNOTFOUND
//-------------------------------------------------------------------

const Status BufMap::remove(File* file, const int pageNo) 
{
    map< pair<File*, const int>, unsigned int>::iterator it;
    pair <File*, const int> key = make_pair(file, pageNo);
    it = realBufMap.find(key);
    if(it == realBufMap.end())
    {
        //can't find it
        return BUFMAPNOTFOUND;
    }
    else
    {
        realBufMap.erase(it);
        return OK;
    }
}
